package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Time;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @author 枝枝
 * @date 2023/7/15
 */
@Slf4j
@Component
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    /**
     * 将任意Java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }


    /**
     * * 将任意Java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，用于处理缓存击穿问题
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {

        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    /**
     * 根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透问题
     *
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFunction
     * @param time
     * @param timeUnit
     * @param <T>
     * @param <ID>
     * @return
     */
    public <T, ID> T resolveCachePenetration(String keyPrefix, ID id, Class<T> type, Function<ID, T> dbFunction, Long time, TimeUnit timeUnit) {
        String key = keyPrefix + id;

        //从redis查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            T t = JSONUtil.toBean(shopJson, type);
            return t;
        }

        //判断命中的是否为空值
        if (shopJson != null) {
            return null;
        }

        //不存在，查询数据库
        T t = dbFunction.apply(id);
        //如果数据库也不存在就返回错误
        if (t == null) {
            //把空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", time, timeUnit);
            return null;
        }

        //存在就写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(t), time, timeUnit);
        return t;
    }


    /**
     * 逻辑过期解决缓存击穿
     *
     * @param id
     * @return
     */
    public <T, ID> T logicalExpirationResolvesCacheBreakdown(String keyPrefix, ID id, Class<T> type, Function<ID, T> dbFunction, Long time, TimeUnit timeUnit) {
        //从redis中查询
        String shopKey = keyPrefix + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        //判断是否命中
        if (StrUtil.isBlank(shopJson)) {
            //未命中
            return null;
        }

        //反序列化
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        T t = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //判断缓存是否过期
        if (expireTime.isBefore(LocalDateTime.now())) {
            //未过期
            return t;
        }

        //已过期
        //尝试获取锁，进行数据重建
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (BooleanUtil.isTrue(isLock)) {
            //获取锁成功
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    T t1 = dbFunction.apply(id);
                    //缓存重建
                    this.setWithLogicalExpire(shopKey, t1, time, timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }

        //返回过期的数据
        return t;
    }

    /**
     * 互斥锁解决缓存击穿
     *
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFunction
     * @param time
     * @param timeUnit
     * @param <T>
     * @param <ID>
     * @return
     */
    public  <T, ID> T mutexLocksSolveCacheBreakdown(String keyPrefix, ID id, Class<T> type, Function<ID, T> dbFunction, Long time, TimeUnit timeUnit) {
        String shopKey = keyPrefix + id;
        //从redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, type);
        }

        //判断命中的是否为空值
        if (shopJson != null) {
            return null;
        }

        T t = null;
        //实现缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            //获取锁
            boolean lock = tryLock(lockKey);
            if (!lock) {
                //获取锁失败
                Thread.sleep(50);
                return mutexLocksSolveCacheBreakdown(keyPrefix, id, type, dbFunction, time, timeUnit);
            }
            //获取锁成功，查询数据库
            t = dbFunction.apply(id);
            //不存在，返回错误
            if (t == null) {
                //把空值写到redis中
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //写入redis
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(t), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return t;
    }

    /**
     * 尝试获取锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


}
